﻿using System;
using System.Collections.Generic;
using System.IO;
using ooWii.IO;
using ooWii.Security;

namespace ooWii.Collections
{
	public class WiiPartitionList : List<WiiPartition>, IDisposable
	{
		#region WiiPartitionList

		SHA1Engine sha1Engine = new SHA1Engine();
		AESEngine aesEngine = new AESEngine();

		public WiiPartitionList( Stream iso )
		{
			byte[] buffer = new byte[ 32 ];

			iso.Position = 0x40000;
			if( iso.Read( buffer, 0, buffer.Length ) != buffer.Length )
			{
				throw new WiiException( "Cannot read Wii partition table" );
			}

			for( int i = 0; i < 4; i++ )
			{
				UInt32 totalPartitions = WiiBuffer.GetUInt32( buffer, i * 8 );
				long partitionInfoTableOffset = WiiBuffer.GetUInt34( buffer, ( i * 8 ) + 4 );

				for( int partition = 0; partition < totalPartitions; partition++ )
				{
					WiiPartition wiiPartition = WiiPartition.Create( iso, partitionInfoTableOffset + ( partition * 8 ), sha1Engine, aesEngine );
					this.Add( wiiPartition );
				}
			}
		}

		#endregion

		#region IDisposable

		public void Dispose()
		{
			aesEngine.Dispose();
			sha1Engine.Dispose();
		}

		#endregion
	}
}
